using Microsoft.AspNetCore.Http;
using System.Text.Json;
using textJson = System.Text.Json;

namespace ZR.ServiceCore.Middleware
{
    /// <summary>
    /// 验证码异常处理中间件
    /// 当验证码功能出现异常时，提供备用方案
    /// </summary>
    public class CaptchaExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private static readonly textJson.JsonSerializerOptions _jsonOptions = new()
        {
            PropertyNamingPolicy = textJson.JsonNamingPolicy.CamelCase,
            WriteIndented = true
        };

        public CaptchaExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex) when (IsCaptchaException(ex))
            {
                // 如果是验证码相关异常，返回简单的文本验证码
                if (context.Request.Path.StartsWithSegments("/captchaImage"))
                {
                    await HandleCaptchaException(context);
                    return;
                }
                
                // 其他验证码相关异常，继续抛出
                throw;
            }
        }

        private static bool IsCaptchaException(Exception ex)
        {
            return ex.Message.Contains("SkiaSharp") || 
                   ex.Message.Contains("Lazy.Captcha") ||
                   ex.Message.Contains("libSkiaSharp");
        }

        private static async Task HandleCaptchaException(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = 200;

            // 生成简单的文本验证码
            var captchaText = GenerateSimpleCaptcha();
            var captchaData = new
            {
                code = 200,
                msg = "操作成功",
                data = new
                {
                    captchaOnOff = true,
                    uuid = Guid.NewGuid().ToString(),
                    img = $"data:image/svg+xml;base64,{GenerateSimpleSvgCaptcha(captchaText)}"
                }
            };

            var json = textJson.JsonSerializer.Serialize(captchaData, _jsonOptions);
            await context.Response.WriteAsync(json);
        }

        private static string GenerateSimpleCaptcha()
        {
            var random = new Random();
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            return new string(Enumerable.Repeat(chars, 4)
                .Select(s => s[random.Next(s.Length)]).ToArray());
        }

        private static string GenerateSimpleSvgCaptcha(string text)
        {
            var svg = $@"
                <svg width='120' height='40' xmlns='http://www.w3.org/2000/svg'>
                    <rect width='120' height='40' fill='#f0f0f0' stroke='#ccc' stroke-width='1'/>
                    <text x='60' y='25' text-anchor='middle' font-family='Arial' font-size='16' fill='#333'>{text}</text>
                </svg>";
            
            var bytes = System.Text.Encoding.UTF8.GetBytes(svg);
            return Convert.ToBase64String(bytes);
        }
    }
}
